package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eic.framework.core.domain.CommonWrapperVFunction;
import com.eic.framework.core.service.ServiceCacheImpl;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.system.domain.dao.*;
import com.ruoyi.system.domain.persist.SysUserPo;
import com.ruoyi.system.domain.wrapper.query.SysUserWrapperQ;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.validation.Validator;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户 业务层处理
 * 
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl extends ServiceCacheImpl<SysUserMapper,SysUser> implements ISysUserService
{
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ISysUserPasswdService sysUserPasswdService;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private ISysPostService sysPostService;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysSeqService sysSeqService;
    @Autowired
    protected Validator validator;

    public SysUserServiceImpl(){
        CommonWrapperVFunction.setFunctionUserNameById((userId) -> {
            SysUser user=getById(userId);
            if(user!=null){
                return user.getNickName();
            }
            return null;
        });
    }
    /**
     * 通过用户名查询用户
     * 
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName)
    {

        LambdaQueryWrapper<SysUser> wrapper=Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUserName,userName);
        return userMapper.selectOne(wrapper);
    }

    /**
     * 查询用户所属角色组
     * 
     * @param userId
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userId)
    {
        LambdaQueryWrapper<SysRole> wrapper= Wrappers.<SysRole>lambdaQuery();
        wrapper.exists("select * from sys_user_role b where b.role_id=sys_role.role_id and b.user_id={0}",userId);
        List<SysRole> list = roleMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(list))
        {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     * 
     * @param userId
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userId)
    {
        List<SysPost> list = sysPostService.selectPostListByUserId(userId);
        if (CollectionUtils.isEmpty(list))
        {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     * 
     * @param userName 用户名称
     * @return 结果
     */
    @Override
    public String checkUserNameUnique(String userName)
    {
        long count = userMapper.selectCount(SysUserWrapperQ.getQueryWrapper(new SysUser().setUserName(userName)));
        if (count > 0){
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkPhoneUnique(SysUser user)
    {
        String userId = StringUtils.isNull(user.getUserId()) ? "-1" : user.getUserId();
        LambdaQueryWrapper<SysUser> wrapper=SysUserWrapperQ.getQueryWrapper(new SysUser().setPhonenumber(user.getPhonenumber()));
        wrapper.select(SysUser::getUserId,SysUser::getPhonenumber);
        SysUser info = userMapper.selectOne(wrapper);
        if (StringUtils.isNotNull(info) && !info.getUserId().equals(userId))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public String checkEmailUnique(SysUser user)
    {
        String userId = StringUtils.isNull(user.getUserId()) ? "-1" : user.getUserId();
        LambdaQueryWrapper<SysUser> wrapper=SysUserWrapperQ.getQueryWrapper(new SysUser().setEmail(user.getEmail()));
        wrapper.select(SysUser::getUserId,SysUser::getEmail);
        SysUser info = userMapper.selectOne(wrapper);
        if (StringUtils.isNotNull(info) && !info.getUserId().equals(userId))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增保存用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean insertUser(SysUserPo user)
    {
        // 新增用户信息
        user.setUserId(sysSeqService.nextUserId());
        boolean succ = super.insert((SysUser)user);
        //密码
        SysUserPasswd passwd=new SysUserPasswd();
        passwd.setUserId(user.getUserId());
        passwd.setPasswdModifyDate(new Date());
        passwd.setPassword(user.getPassword());
        sysUserPasswdService.insert(passwd);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return succ;
    }

    /**
     * 注册用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUserPo user)
    {
        user.setUserId(sysSeqService.nextUserId());
        //密码
        SysUserPasswd passwd=new SysUserPasswd();
        passwd.setUserId(user.getUserId());
        passwd.setPassword(user.getPassword());
        passwd.setPasswdModifyDate(new Date());
        sysUserPasswdService.insert(passwd);
        return super.insert(user);
    }

    /**
     * 修改保存用户信息
     * 
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean updateUser(SysUserPo user)
    {
        String userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        return super.updateById(user);
    }

    /**
     * 用户授权角色
     * 
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(String userId, String[] roleIds)
    {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 新增用户角色信息
     * 
     * @param user 用户对象
     */
    public void insertUserRole(SysUserPo user)
    {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     * 
     * @param user 用户对象
     */
    public void insertUserPost(SysUserPo user)
    {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts))
        {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (Long postId : posts)
            {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     * 
     * @param userId 用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(String userId, String[] roleIds)
    {
        if (StringUtils.isNotEmpty(roleIds))
        {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (String roleId : roleIds)
            {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    @Override
    public boolean matchPasswd(String userId, String passwd) {
        SysUserPasswd userPasswd=sysUserPasswdService.getById(userId);
        return SecurityUtils.matchesPassword(passwd,userPasswd.getPassword());
    }

    @Override
    public boolean updateLoginIp(String userId) {
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        SysUserPasswd userPasswd=new SysUserPasswd();
        userPasswd.setUserId(userId);
        userPasswd.setLoginIp(ip);
        userPasswd.setLoginDate(new Date());
        return sysUserPasswdService.updateById(userPasswd);
    }

    @Override
    public boolean resetPasswd(SysUserPasswd user) {
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setPasswdModifyDate(new Date());
        return sysUserPasswdService.updateById(user);
    }

    /**
     * 通过用户ID删除用户
     * 
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public boolean removeById(Serializable userId)
    {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId((String)userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId((String)userId);
        return super.removeById(userId);
    }

    /**
     * 批量删除用户信息
     * 
     * @param idList 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public boolean removeByIds(Collection<? extends Serializable> idList)
    {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(idList);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(idList);
        return super.removeByIds(idList);
    }

    /**
     * 导入用户数据
     * 
     * @param userList 用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(userList) || userList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList)
        {
            try
            {
                // 验证是否存在这个用户
                SysUser u = selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u))
                {
                    BeanValidators.validateWithException(validator, user);
                    //user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    this.insert(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    BeanValidators.validateWithException(validator, user);
                    user.setUpdateBy(operName);
                    this.updateById(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
